/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package boundary.registration;

import components.utils.ComponentFactory;
import components.utils.CustomVerifier;
import components.TabPanel;
import components.utils.observer.ComboBoxUpdater;
import components.utils.observer.TestsInputTableUpdater;
import control.Application;
import entity.Billing;
import entity.Client;
import entity.Sample;
import entity.ServiceRequest;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import javax.swing.JOptionPane;
import org.joda.time.DateTime;

/**
 *
 * @author Juan
 */
public class PServiceRequestRegistration extends TabPanel {
    
    private ComboBoxUpdater clientsUpdater;
    private TestsInputTableUpdater testsUpdater;

    /**
     * Creates new form PServiceRequestRegistration
     */
    public PServiceRequestRegistration() {
        initComponents();
        
        ComponentFactory.attachVerifier("Por favor seleccione el cliente que realiza la solicitud "
                + "o registre un cliente nuevo si no se encuentra en la lista.", CBClient);
        ComponentFactory.attachVerifier("Por favor especifique el lugar de origen de las muestras.", TFOrigin);
        ComponentFactory.attachVerifier("Por favor seleccione una opción de registro de envío de las muestras.", CBShipmentRecord);
        ComponentFactory.attachVerifier("Por favor seleccione una opción de control de cobros.", CBBilling);
        ComponentFactory.attachVerifier("Por favor seleccione una opción para disposición de muestras.", CBDispositionMethod);
        ComponentFactory.attachVerifier("Por favor especifique la empresa y el número de guía del envío.", TFShipmentRecord);
        ComponentFactory.attachVerifier("Por favor ingrese el número de la orden de servicio.", TFBilling);
        
        clientsUpdater =
                new ComboBoxUpdater(Application.CLIENT_MANAGER.getCollection(),
                CBClient, "<Seleccione un cliente>");
        Application.CLIENT_MANAGER.addObserver(clientsUpdater);
        clientsUpdater.notifyObserver();
        
        testsUpdater =
                new TestsInputTableUpdater(Application.DATABASE_TEST_MANAGER.getCollection());
        Application.DATABASE_TEST_MANAGER.addObserver(testsUpdater);
        pSamplesInput.setTableUpdater(testsUpdater);
    }

    @Override
    protected void removeObservers() {
        Application.CLIENT_MANAGER.removeObserver(clientsUpdater);
        Application.DATABASE_TEST_MANAGER.removeObserver(testsUpdater);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        LServiceOrderNumber = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        CBClient = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        BNewPerson = new javax.swing.JButton();
        TFOrigin = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        CBShipmentRecord = new javax.swing.JComboBox();
        jLabel5 = new javax.swing.JLabel();
        TFShipmentRecord = new javax.swing.JTextField();
        CBBilling = new javax.swing.JComboBox();
        TFBilling = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        CBDispositionMethod = new javax.swing.JComboBox();
        pSamplesInput = new components.panels.PSamplesInput();
        BRegisterOrder = new javax.swing.JButton();
        BCancel = new javax.swing.JButton();
        BNewEnterprise = new javax.swing.JButton();

        jLabel1.setText("Número de Solicitud:");

        LServiceOrderNumber.setText("SA");

        jLabel2.setText("Cliente:");

        CBClient.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "<Seleccione un cliente>" }));

        jLabel3.setText("Lugar de Origen:");

        BNewPerson.setText("Registrar Persona Natural");
        BNewPerson.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BNewPersonActionPerformed(evt);
            }
        });

        jLabel4.setText("Registro de Envío:");

        CBShipmentRecord.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "<Seleccione una opción>", "Empresa de Mensajería", "Personal", "Mensajero" }));
        CBShipmentRecord.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CBShipmentRecordActionPerformed(evt);
            }
        });

        jLabel5.setText("Control de Cobros:");

        TFShipmentRecord.setEnabled(false);

        CBBilling.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "<Seleccione una opción>", "Facturar", "Abono", "Orden de Servicio" }));
        CBBilling.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CBBillingActionPerformed(evt);
            }
        });

        TFBilling.setEnabled(false);

        jLabel6.setText("Disposición de Muestras:");

        CBDispositionMethod.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "<Seleccione una opción>", "Entregar", "Disponer" }));

        BRegisterOrder.setText("Registrar Solicitud");
        BRegisterOrder.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BRegisterOrderActionPerformed(evt);
            }
        });

        BCancel.setText("Cancelar Registro");
        BCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BCancelActionPerformed(evt);
            }
        });

        BNewEnterprise.setText("Registrar Empresa");
        BNewEnterprise.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BNewEnterpriseActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(pSamplesInput, javax.swing.GroupLayout.DEFAULT_SIZE, 980, Short.MAX_VALUE)
                    .addComponent(CBClient, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(TFOrigin)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(CBShipmentRecord, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(TFShipmentRecord))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(CBBilling, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(TFBilling))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(LServiceOrderNumber))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(BNewPerson)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(BNewEnterprise))
                            .addComponent(jLabel3)
                            .addComponent(jLabel4)
                            .addComponent(jLabel5)
                            .addComponent(jLabel6)
                            .addComponent(CBDispositionMethod, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(BRegisterOrder)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(BCancel)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(LServiceOrderNumber))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(CBClient, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(BNewPerson)
                    .addComponent(BNewEnterprise))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(TFOrigin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(CBShipmentRecord, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(TFShipmentRecord, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(CBBilling, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(TFBilling, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel6)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(CBDispositionMethod, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(pSamplesInput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(BRegisterOrder)
                    .addComponent(BCancel))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void CBShipmentRecordActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CBShipmentRecordActionPerformed
        if (CBShipmentRecord.getSelectedIndex() == 1) {
            TFShipmentRecord.setEnabled(true);
        } else {
            TFShipmentRecord.setText(null);
            TFShipmentRecord.setEnabled(false);
        }
    }//GEN-LAST:event_CBShipmentRecordActionPerformed

    private void BCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BCancelActionPerformed
        buttonTabComponent.closeTab();
    }//GEN-LAST:event_BCancelActionPerformed

    private void BRegisterOrderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BRegisterOrderActionPerformed
        pSamplesInput.stopEditing();
        //New service request instance to store the data.
        ServiceRequest newServiceRequest = new ServiceRequest();
        
        //Custom verifier instance used to validate the fields.
        CustomVerifier currentVerifier;
        
        //Client selection validation.
        currentVerifier = (CustomVerifier) CBClient.getInputVerifier();
        if (currentVerifier.isValid()) {
            newServiceRequest.setClient((Client) CBClient.getSelectedItem());
        } else {
            return;
        }
        
        //Origin initial validation.
        currentVerifier = (CustomVerifier) TFOrigin.getInputVerifier();
        if (currentVerifier.isValid()) {
            newServiceRequest.setOrigin(TFOrigin.getText().trim());
        } else {
            return;
        }
        
        //Shipment record initial validation.
        currentVerifier = (CustomVerifier) CBShipmentRecord.getInputVerifier();
        if (currentVerifier.isValid()) {
            switch (CBShipmentRecord.getSelectedIndex()) {
                case 1:
                    currentVerifier = (CustomVerifier) TFShipmentRecord.getInputVerifier();
                    if (currentVerifier.isValid()) {
                        newServiceRequest.setShipmentRecord(TFShipmentRecord.getText().trim());
                        break;
                    } else {
                        return;
                    }

                case 2:
                    newServiceRequest.setShipmentRecord(ServiceRequest.PERSONAL_SHIPMENT);
                    break;

                case 3:
                    newServiceRequest.setShipmentRecord(ServiceRequest.MESSENGER_SHIPMENT);
                    break;

                default:
                    System.err.println("Error in Shipment record initial validation.");
            }
        } else {
            return;
        }
        
        //Billing validation.
        currentVerifier = (CustomVerifier) CBBilling.getInputVerifier();
        Billing newBilling = new Billing();
        if (currentVerifier.isValid()) {
            switch (CBBilling.getSelectedIndex()) {
                case 1:
                    newBilling.setBillingPending(true);
                    break;

                case 2:
                    currentVerifier = (CustomVerifier) TFBilling.getInputVerifier();
                    try {
                        Double deposit = Double.parseDouble(TFBilling.getText().trim());
                        newBilling.setDeposit(deposit);
                        newBilling.setBillingPending(true);
                        break;
                    } catch (NullPointerException e) {
                        currentVerifier.forceWrongInput("Por favor especifique el monto del abono realizado por el cliente.");
                        return;
                    } catch (NumberFormatException e) {
                        currentVerifier.forceWrongInput("El valor del abono especificado no es válido. "
                                + "Por favor utilice solo números.");
                        TFBilling.setText(null);
                        return;
                    }

                case 3:
                    currentVerifier = (CustomVerifier) TFBilling.getInputVerifier();
                    if (currentVerifier.isValid()) {
                        newBilling.setServiceOrder(TFBilling.getText());
                        newBilling.setBillingPending(false);
                    } else {
                        return;
                    }
                    break;

                default:
                    System.err.println("Error in billing inital validation.");
            }
        } else {
            return;
        }
        newServiceRequest.setBilling(newBilling);
                
        //Disposition method validation.
        currentVerifier = (CustomVerifier) CBDispositionMethod.getInputVerifier();
        int dispositionMethod = -1;
        if (currentVerifier.isValid()) {
            switch (CBDispositionMethod.getSelectedIndex()) {
                case 1:
                    dispositionMethod = Sample.DISPOSITION_METHOD_DELIVER;
                    break;
                case 2:
                    dispositionMethod = Sample.DISPOSITION_METHOD_DISPOSE;
                    break;

                default:
                    System.err.println("Error in disposition method validation.");
            }
        } else {
            return;
        }
        newServiceRequest.setDispositionMethod(dispositionMethod);
        
        //Sample input validation.
        List samples;
        if (!pSamplesInput.validFields()) {
            return;
        } else {
            //Set disposition method for the samples returned.
            samples = pSamplesInput.getSamples();
            
            for (Iterator it = samples.iterator(); it.hasNext();) {
                Sample currentSample = (Sample) it.next();
                currentSample.setDispositionMethod(dispositionMethod);
                currentSample.setServiceRequest(newServiceRequest);
            }
        }
        newServiceRequest.setSamples(samples);
        
        //Setting registration date.
        newServiceRequest.setRegistrationDate(new DateTime());
        
        //Placeholder
        newServiceRequest.setId(Math.abs(new Random().nextInt() % 5000));
        Application.SERVICE_REQUEST_MANAGER.addObject(newServiceRequest);
        JOptionPane.showMessageDialog(this.getTopLevelAncestor(),
                "La solicitud se ha registrado con éxito.",
                "Información", JOptionPane.INFORMATION_MESSAGE);
        int choice = JOptionPane.showConfirmDialog(getTopLevelAncestor(),
                                        "¿Desea imprimir los códigos de barras para las muestras registradas?",
                                        "Impresión de Códigos de Barras", JOptionPane.YES_NO_OPTION,
                                        JOptionPane.QUESTION_MESSAGE);
        if (choice == JOptionPane.YES_OPTION) {
            control.ControlSample.printBarcodes(newServiceRequest.getSamples());
        }
        buttonTabComponent.closeTab();
        
        //Pass to control and persist.
    }//GEN-LAST:event_BRegisterOrderActionPerformed

    private void CBBillingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CBBillingActionPerformed
        switch (CBBilling.getSelectedIndex()) {
            case 0:
            case 1:
                TFBilling.setEnabled(false);
                TFBilling.setText(null);
                break;
            case 2:
            case 3:
                TFBilling.setEnabled(true);
        }
    }//GEN-LAST:event_CBBillingActionPerformed

    private void BNewPersonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BNewPersonActionPerformed
        Application.F_MAIN.openPersonRegistrationPanel();
    }//GEN-LAST:event_BNewPersonActionPerformed

    private void BNewEnterpriseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BNewEnterpriseActionPerformed
        Application.F_MAIN.openEnterpriseRegistrationPanel();
    }//GEN-LAST:event_BNewEnterpriseActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BCancel;
    private javax.swing.JButton BNewEnterprise;
    private javax.swing.JButton BNewPerson;
    private javax.swing.JButton BRegisterOrder;
    private javax.swing.JComboBox CBBilling;
    private javax.swing.JComboBox CBClient;
    private javax.swing.JComboBox CBDispositionMethod;
    private javax.swing.JComboBox CBShipmentRecord;
    private javax.swing.JLabel LServiceOrderNumber;
    private javax.swing.JTextField TFBilling;
    private javax.swing.JTextField TFOrigin;
    private javax.swing.JTextField TFShipmentRecord;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private components.panels.PSamplesInput pSamplesInput;
    // End of variables declaration//GEN-END:variables
}
